package com.jiefutong.zyt.http;

import android.content.Context;

import com.jiefutong.zyt.utils.PrefsUtil;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * http请求提供器
 */
public class HttpProvider {
    private static HttpProvider instance;
    private String mToken;
    private OkHttpClient okHttpClient;
    private Context context;
    Call call;

    private HttpProvider() {
        OkHttpClient.Builder builder=new OkHttpClient.Builder();
        setOkHttpClient(builder);
        okHttpClient=builder.build();

    }

    /**
     * 获取http请求提供器
     *
     * @return HttpProvider实例
     */
    public static HttpProvider getInstance() {
        try {
            if (instance == null) {
                instance = new HttpProvider();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return instance;
    }

    /**
     * 获取http请求类
     *
     * @return okHttpClient
     */
    public OkHttpClient getOkHttpClient() {
        return okHttpClient;
    }

    /**
     * 将请求加入请求队列
     *
     * @param req      请求信息
     * @param callback 响应回调
     */
    public void enqueue(Request req, Callback callback, Context context) {
        try {
            this.context = context;
            call= okHttpClient.newCall(req);
            call.enqueue(callback);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 取消请求
     *
     * @param requestFlag 请求标识
     */
    public void cancelRequest(Object requestFlag) {
        /*okHttpClient.cancel(requestFlag);*/
        call.cancel();

    }

    private void setOkHttpClient(OkHttpClient.Builder builder) {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(
                        X509Certificate[] chain,
                        String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(
                        X509Certificate[] chain,
                        String authType) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    //return null;
                    X509Certificate[] x509Certificates = new X509Certificate[0];
                    return x509Certificates;
                }

            }};

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            builder.connectTimeout(60 * 1000, TimeUnit.MILLISECONDS);
            builder.readTimeout(60 * 1000, TimeUnit.MILLISECONDS);

            builder.sslSocketFactory(sslSocketFactory);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            // 拦截所有请求
            builder.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    Request.Builder builder= request.newBuilder();
                    try{
                        String token  =PrefsUtil.getString(context, "token","");;

                        builder.addHeader("Accept", "application/json");
                        builder.addHeader("Authorization", token);
                    }catch (Exception e){

                    }

                    return chain.proceed(builder.build());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
